import { examPlanApi } from '@/api';
import { DATETIMEFORMAT, pageOpeTypeEnum } from '@/common';
import { CategoryCascader } from '@/components/CategoryCascader';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import { StudyObjectSelect } from '@/components/StudyObjectSelect';
import YmCollaPanes from '@/components/YmCollaPanes';
import { useAppSelector } from '@/redux/store';
import { getIndustryList } from '@/redux/toolkitSlice/CommonDataSlice';
import { EditOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { App, Button, DatePicker, Form, Input, InputNumber, Select, Space, TreeSelect } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { isEmpty } from 'lodash-es';
import { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { YmAddPageLayout, type YmAddPageLayoutProps } from 'ym-design';
import { useEntListSelectTreeProps } from '../AddStudyPlan/common';
import OStyle from './index.less';

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 10 },
};

const REPEATTIMESOPTIONS = [
  { value: 0, label: '无法补考' },
  { value: 1, label: '补考1次' },
  { value: 2, label: '补考2次' },
  { value: 3, label: '补考3次' },
  { value: 4, label: '补考4次' },
  { value: 5, label: '补考5次' },
];

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const { PaneItem } = YmAddPageLayout;

function AddExamPlan() {
  const dispatch = useDispatch();
  const [searchParam] = useSearchParams();
  const type = searchParam.get('type');
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const [deflVal, setDefalVal] = useState<Source[]>([]);
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const { tradeMap } = useAppSelector((state) => state.commonData);
  const [form] = Form.useForm();
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([1, 2]);
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });
  const [classFormItemProps, initRef] = CategoryCascader.useFieldLevelTwo();
  const [choicedTestPaper, setChoicedTestPaper] = useState<{
    id: string;
    name: string;
    isCharge: number;
    sourceType: string;
  }>(); //选择试卷
  const [modalOpen, setModalOpen] = useState<number>();
  const [examinMaxCounts, setExaminMaxCounts] = useState<number[]>(); //考题最大题数

  useEffect(() => {
    dispatch(getIndustryList());
  }, []);

  //学习对象企业配置
  const EntSelectTree = useEntListSelectTreeProps({
    onSuccess(data) {
      const entList = form.getFieldsValue().entList;
      if (!entList) {
        // 没有就是需要默认给全部
        form.setFieldsValue({
          entList: data.map(({ title, id }) => ({
            entId: id,
            entName: title,
          })),
        });
      }
    },
  });

  //证书列表
  const [certificateOptions, setCertificateOptions] =
    useState<{ value: string; label: string; certType: string | number }[]>();

  // 协会--考试类型
  const modelType = Form.useWatch('modelType', form); // 1：常规考试，2：练习

  //学习时间选择限制
  const disabledRangeTime: RangePickerProps['disabledTime'] = (_, type) => {
    // if (type === 'start') {}
    const range = (start: number, end: number) => {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    };
    const curHour = dayjs().get('hour');
    const curMin = dayjs().get('minute');

    return {
      disabledHours: () => range(0, 24).splice(0, curHour),
      disabledMinutes: () => range(0, 60).splice(0, curMin),
    };
  };

  useEffect(() => {
    if (type === pageOpeTypeEnum['add']) {
      const initialFormData: any = {
        studyTime: [dayjs().add(15, 'minutes'), dayjs().add(1470, 'minutes')],
        questionTypeList: [
          { questionType: 100, num: undefined },
          { questionType: 200, num: undefined },
          { questionType: 300, num: undefined },
        ],
      };

      if (organizationType === 0) {
        //企业
        initialFormData.repeatTimes = 0;
      } else {
        initialFormData.modelType = 1;
      }
      form.setFieldsValue(initialFormData);
    }
  }, [type]);

  useEffect(() => {
    //常规考试
    if (modelType === 1) {
      //证书
      if (isEmpty(certificateOptions)) {
        examPlanApi.getCertInfo().then((res: any) => {
          if (res.code === '200') {
            setCertificateOptions(
              res?.data?.map((item: any) => ({ value: item.certId, label: item.certName, certType: item.certType })),
            );
          }
        });
      }
    }

    // 练习题
    if (modelType === 2) {
      //获取题目最大数量
      examPlanApi.getQuestionNum().then((res: any) => {
        if (res.code == '200') {
          const tempMaxCounts = res.data
            ?.sort((prevItem: any, nextItem: any) => prevItem.questionType - nextItem.questionType) //升序排序
            .map((item: any) => Number(item.num));
          setExaminMaxCounts(tempMaxCounts);
        }
      });
    }
  }, [modelType, certificateOptions]);

  //添加试卷
  const handleSourceModalChange = (values: Source[], menuActiveKey: string) => {
    const sourceType = menuActiveKey.includes('government') ? '100' : '200'; // '100':企业协会自建 ，200：平台
    console.log('--添加试卷--values--:', values);
    const { id, name, origin } = values[0];
    setDefalVal([...values]);
    setChoicedTestPaper({ id, name, isCharge: (origin as any).isCharge || 0, sourceType });
  };

  //发布
  const onSubPublish = () => {
    form
      .validateFields()
      .then((values) => {
        console.log('--AddExamPlan--values--:', values);
        const { title, studyObject, studyTime, modelType, certId, classId, entList, questionTypeList, repeatTimes } =
          values;
        if (modelType !== 2 && !choicedTestPaper) {
          return message.warning('请选择试卷');
        }
        //学习时间
        let startTime, endTime;
        if (studyTime) {
          if (!studyTime[0].isAfter(dayjs())) {
            return message.warning('计划开始时间必须大于当前时间');
          }
          if (studyTime[1].diff(studyTime[0], 'second') >= 3 * 3600 * 24 * 365) {
            return message.warning('有效期设置最大为3年');
          }
          startTime = studyTime[0].format(DATETIMEFORMAT);
          endTime = studyTime[1].format(DATETIMEFORMAT);
        }

        //通用字段和固定字段
        let subValues: any = {
          entId,
          title,
          studyObject,
          addSource: organizationType === 1 ? 2 : 1,
          // isCharge: isCharge, // 1:付费，0：免费
          issue: 1, //1:发布，0：保存
          platfromType: 600,
          type: 300,
          studyType: 300,
        };
        //--协会
        if (organizationType === 1) {
          subValues = {
            ...subValues,
            entList,
            modelType,
            classId,
          };
          if (modelType === 2) {
            //--练习卷
            subValues.isCharge = 0;
            subValues.questionTypeList = questionTypeList;
          } else {
            const { sourceType, isCharge, id: relationId } = choicedTestPaper!;

            //证书
            // certId
            if (!isEmpty(certificateOptions)) {
              const currCerDetail = certificateOptions?.find((item: any) => item.value === certId);
              if (!isEmpty(currCerDetail)) {
                const { certType, label: certName } = currCerDetail;
                subValues.certDto = { certId, certType, certName };
              }
            }

            subValues = {
              ...subValues,
              startTime,
              endTime,
              relationId,
              sourceType: Number(sourceType),
              isCharge,
            };
          }
        } else {
          //--企业
          const { sourceType, isCharge, id: relationId } = choicedTestPaper!;
          //学习时间
          const startTime = studyTime[0].format(DATETIMEFORMAT);
          const endTime = studyTime[1].format(DATETIMEFORMAT);

          subValues = {
            ...subValues,
            startTime,
            endTime,
            sourceType: Number(sourceType),
            isCharge,
            relationId,
            repeatTimes,
          };
        }

        // 编辑
        setLoadingDetail({ viewLoading: true, subBtnDis: true });

        // 企业，协会,同一个接口
        examPlanApi
          .createExaminPlan(subValues)
          .then((res: any) => {
            const { code, data, msg } = res;
            // console.log('--res--:', res);
            if (code === '200') {
              if (data === 1) {
                confirm({
                  title: '发布失败',
                  content: msg,
                  centered: true,
                  okText: '前往',
                  onOk: () => {
                    if (loginRole == '1' || loginRole == '0') {
                      navigator('/safeService/buyService');
                    } else {
                      message.warning('您暂无权限，请联系企业管理人员！');
                    }
                  },
                });
              } else if (data.promptMessage) {
                confirm({
                  title: '发布成功',
                  content: data.promptMessage,
                  centered: true,
                  okText: '前往',
                  onOk: () => {
                    if (loginRole == '1' || loginRole == '0') {
                      navigator('/safeService/bitAllocation');
                    } else {
                      message.warning('您暂无权限，请联系企业管理人员！');
                    }
                  },
                });
              } else {
                message.success((type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '成功');
                // navigator(-1);
                navigator('/plannedManage/examPlan');
              }
            }
          })
          .catch((err: any) => {
            console.log('--AddExaminPlan--createExaminPlan--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ viewLoading: false, subBtnDis: false });
          });
      })
      .catch((err) => {
        setLoadingDetail({ viewLoading: false, subBtnDis: false });
        console.log('--AddExamPlan--form--err--:', err);
      });
  };
  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          // navigator(-1);
          navigator('/plannedManage/examPlan');
        },
      },
      rightOperationDom: [
        <Button key="public" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={onSubPublish}>
          发布
        </Button>,
      ],
      destroyInactiveTabPane: false,
    }),
    [choicedTestPaper, loadingDetail],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      {/* <ViewLoading show={loadingDetail.viewLoading} /> */}
      <PaneItem tabKey="tab1" label="添加考试计划" className="pane_tab1">
        <Form className={OStyle.form_cont} layout="horizontal" labelAlign="right" form={form} {...formItemLayout}>
          <YmCollaPanes
            collPanesActiveKeys={collPanesActiveKeys}
            paneKey={1}
            collapsible={false}
            headerTitle="基本信息"
          >
            <Form.Item label="计划名称" name="title" rules={requireRules('请输入计划名称')}>
              <Input showCount maxLength={18} placeholder="请输入"></Input>
            </Form.Item>
            {modelType !== 2 && (
              <Form.Item label="选择时间" name="studyTime" rules={requireRules('请输入学习时间')}>
                <DatePicker.RangePicker
                  format="YYYY-MM-DD HH:mm"
                  showTime={{ format: 'HH:mm' }}
                  disabledDate={(date) => {
                    return date.isBefore(dayjs().startOf('day'));
                  }}
                  placement="topRight"
                  popupStyle={{ height: 100 }}
                  disabledTime={disabledRangeTime}
                ></DatePicker.RangePicker>
              </Form.Item>
            )}
            {modelType === 1 && !isEmpty(certificateOptions) && (
              <Form.Item label="颁发证件" name="certId">
                <Select options={certificateOptions} placeholder="可选择考试通过后颁发证件（选填）" />
              </Form.Item>
            )}
            {organizationType === 1 ? (
              <Form.Item label="学习对象" required wrapperCol={{ span: 19 }}>
                <Space>
                  <Form.Item
                    name="entList"
                    noStyle
                    {...EntSelectTree.fieldProps}
                    rules={requireRules('请选择学习对象企业')}
                  >
                    <TreeSelect {...EntSelectTree.treeSelectProps}></TreeSelect>
                  </Form.Item>
                  <Form.Item name="studyObject" noStyle rules={requireRules('请选择学习对象人员')}>
                    <StudyObjectSelect optionsType={1} />
                  </Form.Item>
                </Space>
              </Form.Item>
            ) : (
              <>
                <Form.Item name="repeatTimes" label="补考设置">
                  <Select options={REPEATTIMESOPTIONS} />
                </Form.Item>
                <Form.Item name="studyObject" label="学习对象" rules={requireRules('请选择学习对象人员')}>
                  <StudyObjectSelect placeholder="请选择学习对象" optionsType={1} />
                </Form.Item>
              </>
            )}
            {organizationType === 1 && (
              <>
                <Form.Item label="考试类型" name="modelType">
                  <Select
                    options={[
                      { value: 1, label: '常规卷' },
                      { value: 2, label: '练习卷' },
                    ]}
                  />
                </Form.Item>
                <Form.Item label="分类" name="classId" {...classFormItemProps} rules={requireRules('请选择分类')}>
                  <CategoryCascader />
                </Form.Item>
              </>
            )}
            {!isEmpty(tradeMap) && modelType !== 2 && (
              <Form.Item label="添加试卷" required>
                {choicedTestPaper ? (
                  <Space>
                    <span>{choicedTestPaper.name}</span>
                    <EditOutlined
                      style={{ color: 'rgb(255, 109, 59)' }}
                      onClick={() => {
                        setModalOpen(Math.random());
                      }}
                    />
                  </Space>
                ) : (
                  <PlusCircleOutlined
                    style={{ color: 'rgb(255, 109, 59)' }}
                    onClick={() => {
                      setModalOpen(Math.random());
                    }}
                  />
                )}
              </Form.Item>
            )}
            <SourceSelectModal
              openDep={modalOpen}
              preSet="考试计划"
              params={{ entId }}
              columnsRender={{ tradeMap }}
              value={deflVal}
              onChange={handleSourceModalChange} //放在Form.Item里面只会识别第一个参数作为value
              // modalWidth={1176}
              // menuLeftWidth={168}
            />

            {modelType === 2 && examinMaxCounts && (
              <Form.List name="questionTypeList">
                {(fields, { add, remove }, { errors }) => (
                  <>
                    {fields.map((field, index) => (
                      <Form.Item key={field.key} style={{ marginBottom: '0px' }}>
                        <Form.Item noStyle name={[field.name, 'questionType']} hidden>
                          <InputNumber min={0} max={100} />
                        </Form.Item>
                        <Form.Item
                          label={(index === 0 ? '单选题' : index === 1 ? '多选题' : '判断题') + '数量'}
                          name={[field.name, 'num']}
                          rules={requireRules('请输入题目数量')}
                        >
                          <InputNumber
                            placeholder="请输入题目数量"
                            min={0}
                            max={examinMaxCounts[index]}
                            style={{ width: '140px' }}
                          />
                        </Form.Item>
                      </Form.Item>
                    ))}
                  </>
                )}
              </Form.List>
            )}
          </YmCollaPanes>
        </Form>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddExamPlan;
